package vip.xiaonuo.modular.attendancerecord.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.dynamic.DynamicCell;
import vip.xiaonuo.dynamic.DynamicCellValue;
import vip.xiaonuo.dynamic.DynamicRow;
import vip.xiaonuo.dynamic.DynamicTable;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.service.MemberUserService;
import vip.xiaonuo.modular.attendancegroup.entity.AttendanceGroup;
import vip.xiaonuo.modular.attendancegroup.service.AttendanceGroupService;
import vip.xiaonuo.modular.attendancerecord.entity.AttendanceRecord;
import vip.xiaonuo.modular.attendancerecord.mapper.AttendanceRecordMapper;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceDoRosterParam;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRecordParam;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRecordRosteringParam;
import vip.xiaonuo.modular.attendancerecord.param.AttendanceRosteringQueryParam;
import vip.xiaonuo.modular.attendanceshift.AttendanceShiftOptionVo;
import vip.xiaonuo.modular.attendanceshift.entity.AttendanceShift;
import vip.xiaonuo.modular.attendanceshift.service.AttendanceShiftService;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

@Service
public class AttendanceRosteringService extends AttendancePlanBaseService{

    @Resource
    private AttendanceRecordMapper mapper;

    @Resource
    private AttendanceGroupService groupService;


    public DynamicTable rostering(AttendanceRecordRosteringParam param) {
        DynamicTable table = new DynamicTable();
        String y_m = param.getYear_month();
        String[] arr = y_m.split("-");
        y_m = arr[0] + (arr[1].length()==1 ? "0" + arr[1] : arr[1]);
        Long group_id = param.getId();

        // 获取当前考勤组所有的考勤计划
        Map<String,AttendanceRecord> recordMap = this.getExistAttendanceRosteringInfo(new AttendanceRosteringQueryParam(group_id,y_m));
        int year = Integer.parseInt(param.getYear_month().split("-")[0]);
        int month =  Integer.parseInt(param.getYear_month().split("-")[1]);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE,1);
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);


        Calendar today_cal = Calendar.getInstance();
        today_cal.set(Calendar.HOUR_OF_DAY,0);
        today_cal.set(Calendar.MINUTE,0);
        today_cal.set(Calendar.SECOND,0);
        Date today = today_cal.getTime();

        int days = cal.getActualMaximum(Calendar.DATE); //这个月的天数
        List<MemberUser> users = getMemberUsers(param.getOrgIds());

        List<DynamicRow> rows = new LinkedList<>();
        for(MemberUser user : users){
            DynamicRow row = new DynamicRow();
            List<DynamicCell> stableCells = new ArrayList<>();
            stableCells.add(new DynamicCell("userId",new DynamicCellValue(user.getId())));
            stableCells.add(new DynamicCell("userName",new DynamicCellValue(user.getName())));
            row.setStableCells(stableCells);

            List<DynamicCell> dynamicCells = new ArrayList<>();
            for(int i = 1 ; i <= days ; i++){
                cal.set(Calendar.DATE,i);
                Date date = cal.getTime();
                String key = user.getId() + "##" + sdf_ymd.format(date);
                if (recordMap.containsKey(key)){
                    AttendanceRecord record  = recordMap.get(key);
                    dynamicCells.add(new DynamicCell("date_" + i, new DynamicCellValue(record,user.getId(),date,!date.before(today)) ));
                }else{
                    dynamicCells.add(new DynamicCell("date_" + i, new DynamicCellValue("休息",user.getId(),date,!date.before(today))));
                }
            }
            row.setDynamicCells(dynamicCells);
            rows.add(row);
        }
        table.setRows(rows);
        return table;
    }

    private Map<String,AttendanceRecord> getExistAttendanceRosteringInfo(AttendanceRosteringQueryParam param){
        Map<String,AttendanceRecord> map = new HashMap<>();
        List<AttendanceRecord> records = mapper.getRecordsByGroupAndMonth(param);

        for(AttendanceRecord record : records){
            String key = record.getMemberUserId() + "##" + sdf_ymd.format(record.getStartDate());
            map.put(key,record);
        }
        return map;
    }

    public List<AttendanceShiftOptionVo> shifts(AttendanceRecordRosteringParam param) {
        List<AttendanceShift> shifts = getAttendanceShifts(param.getAttendanceShiftIds());

        List<AttendanceShiftOptionVo> options= new LinkedList<>();
        options.add(new AttendanceShiftOptionVo(0L,"休息"));
        for (AttendanceShift shift : shifts){
            options.add(new AttendanceShiftOptionVo(shift));
        }

        return options;
    }

    public void doRoster(AttendanceDoRosterParam param) {
        Long record_id = param.getOriginal_id();
        MemberUser user = userService.getById(param.getMemberUserId());
        if(user == null ){
            throw new ServiceException(500,"用户不存在");
        }

        if(param.getAttendanceShiftId()==0L){// 休息
            AttendanceRecord record = recordService.getById(record_id);
            if(record!=null){
                recordService.removeById(record);
            }
            return;
        }

        AttendanceShift shift = shiftService.getById(param.getAttendanceShiftId());
        if(shift == null ){
            throw new ServiceException(500,"班次不存在");
        }

        AttendanceGroup group = groupService.getById(param.getGroup_id());
        if(group == null ){
            throw new ServiceException(500,"考勤组不存在");
        }

        try {
            String date_str = sdf_ymd.format( sdf_full.parse(param.getDate()));
            Date startDate = sdf_full.parse(date_str + " "+ shift.getWorkTime());
            Date endDate = sdf_full.parse(date_str + " "+ shift.getOffWorkTime());
            if(endDate.before(startDate)){
                endDate.setDate(endDate.getDate() + 1);
            }

            AttendanceRecord record = recordService.getById(record_id);
            if(record == null){
                record = new AttendanceRecord();
            }
            record.setAttendanceGroupId(param.getGroup_id());
            record.setAttendanceShiftId(shift.getId());
            record.setUserName(user.getName());
            record.setGroupName(group.getGroupName());
            record.setShiftName(StringUtils.isEmpty(shift.getShiftShortName())? shift.getShiftName() : shift.getShiftShortName());

            record.setMemberUserId(user.getId());
            record.setStartDate(startDate);
            record.setEndDate(endDate);
            record.setIsLate(0);
            record.setIsLeaveEarly(0);
            record.setIsAddition(0);
            record.setIsAbsenceDuty(1);

            AttendanceRecordParam p = new AttendanceRecordParam();
            p.setMemberUserId(user.getId());
            p.setStartDate(date_str.replace("-",""));
            List<AttendanceRecord> records = recordMapper.getRecordsByUserAndDate(p);
            this.checkRepeat(user,record,records);

            recordService.saveOrUpdate(record);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ServiceException(500,"保存失败，日期转换出错！");
        }
    }
}
